import {createRouter, createWebHistory} from 'vue-router'
import {ElMessage} from "element-plus";
import {reactive} from "vue";
import Home from "@/views/global-Views/Home.vue";

/**
 * 以角色作为模块划分的依据，将模块划分未游客、管理员、卖家、普通用户、专家（未划分模块）、银行用户（未划分模块）
 * @type {Router}
 */
const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: '游客',
            meta: {
                requiresAuth: false,
            },
            redirect: '/login',
        },
        {
            path: '/cloud-drive',
            name: '权限用户',
            component: () => import('@/views/global-Views/Manager.vue'),
            meta: {
                requiresAuth: true,
            },
            // 修正后的路由配置
            redirect: 'cloud-drive/home',  // 相对路径重定向
            children: [
                {path: '/cloud-drive/home', name: '主页', component: () => import('@/views/global-Views/Home.vue')},
                {path: '/cloud-drive/profile', name: '个人中心', component: () => import('@/views/global-Views/UpdateInfo.vue')},
                {path: '/cloud-drive/fileManage', name: '文件管理', component: () => import('@/views/cloud-drive-file/FileManage.vue')},
                {path: '/cloud-drive/share/DownloadLink', name: '下载链接', component: () => import('@/views/cloud-drive-file/Share/DownloadLink.vue')},
                {path: '/cloud-drive/fileManage/picture', name: '图片管理', component: () => import('@/views/cloud-drive-file/FileManage/picture.vue')},
                {path: '/cloud-drive/fileManage/video', name: '视频管理', component: () => import('@/views/cloud-drive-file/FileManage/video.vue')},
                {path: '/cloud-drive/fileManage/document', name: '文档管理', component: () => import('@/views/cloud-drive-file/FileManage/document.vue')},
                {path: '/cloud-drive/recycle', name: '回收站', component: () => import('@/views/cloud-drive-file/Recycle.vue')},
                {path: '/cloud-drive/share', name: '共享中心', component: () => import('@/views/cloud-drive-file/Share.vue')}
            ]
        },
        {
            path: '/login',
            name: '登录页面',
            component: () => import('@/views/global-Views/Login.vue'),
        },
        {
            path: '/register',
            name: '注册页面',
            component: () => import('@/views/global-Views/Register.vue')
        },
    ]
})

// 获取localStorage
function getLocalStorage() {
    const data = reactive({
        user: JSON.parse(localStorage.getItem('system-user') || '{}'),
    })
    return data.user
}

// 守护路由
router.beforeEach((to, from, next) => {
    // 检查目标路径是否需要鉴权
    if (to.matched.some(record => record.meta.requiresAuth)) {
        const user = getLocalStorage();
        if (!user || Object.keys(user).length === 0) {
            ElMessage('未登录，请先登录！')
            next({path: '/login'})
        } else {
            next()
        }
    } else {
        next()
    }
})
export default router
